package com.base.web.auth.controller;

import com.base.web.auth.service.UserService;
import com.base.web.core.common.JsonResult;
import com.base.web.model.master.auth.User;
import com.google.code.kaptcha.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.Objects;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: RENTIE
 * Date: 2018-07-04 11:23
 */
@RestController
public class AuthController {

    private Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     *
     * @param map rememberMe 记住我 选择时值为"1"
     *            userName  用户名
     *            password  密码
     * @return
     */
    @PostMapping("/dologin")
    public JsonResult dologin(@RequestParam Map<String, String> map) {

        // 从session获取正确的验证码
        Session session = SecurityUtils.getSubject().getSession();

        //正确验证码
        String validateCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);

        //页面传来的验证码
        String vercode = map.get("vercode");

        //验证码验证
        if (!Objects.equals(validateCode.toLowerCase(), vercode.toLowerCase())) {
            logger.error("验证码错误");
            return JsonResult.fail("验证码错误");
        }

        String rememberMe = map.get("rememberMe");

        String loginName = map.get("loginName");

        String password = map.get("password");

        // shiro认证
        Subject currentUser = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(loginName, password);
        // 设置是否'记住我'
        token.setRememberMe(Objects.equals("1", rememberMe));
        try {
            currentUser.login(token);
        } catch (UnknownAccountException e) {
            logger.error("账户不存在={}", e.getMessage());
            return JsonResult.fail("账户不存在");
        } catch (DisabledAccountException e) {
            logger.error("账户已被禁用={}", e.getMessage());
            return JsonResult.fail("账户已被禁用");
        } catch (AuthenticationException e) {
            logger.error("密码错误={}", e.getMessage());
            return JsonResult.fail("密码错误");
        } catch (Exception e) {
            logger.error("登陆异常={}", e.getMessage());
            return JsonResult.fail("登陆异常");
        }
        if (currentUser.isAuthenticated()) {
            logger.info(loginName+" ===== 登录成功");
            User user = new User();
            user.setLoginName(loginName);
            //返回用户信息
            user = userService.selectOne(user);
            //用户信息存入session
            session.setAttribute("user",user);
            return JsonResult.success(user);
        } else {
            return JsonResult.fail("登陆异常");
        }
    }
}
